import React from 'react';
import { connect } from 'dva';
import { Form, Row, Col, Input, Button, Icon, DatePicker } from 'antd';
import { routerRedux } from 'dva/router';
import moment from 'moment';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};

const AdvancedSearchForm = Form.create({

    mapPropsToFields({ query }) {
        const fields = {}
        Object.keys(query).forEach((key) => { fields[key] = { value: query[key] }; });
        return fields;
    }

})(({ dispatch, form, query }) => {

  function handleSearch(e) {
    e.preventDefault();
    form.validateFields((err, fieldsValue) => {
        if (err) {
          return;
        }
        const regTime = fieldsValue['reg_time'];
        const values = {
          ...fieldsValue,
          'reg_time[]': regTime && [regTime[0].format('YYYY-MM-DD'), regTime[1].format('YYYY-MM-DD')],
        }
        delete values.reg_time;
        dispatch(routerRedux.push({
            pathname: '/users',
            query: values
        }));
    });
  }

  function handleReset() {
        dispatch(routerRedux.push({
            pathname: '/users',
            query: {}
        }));
  }

  const { getFieldDecorator } = form;
  return (
    <Form
      className="ant-advanced-search-form"
      onSubmit={handleSearch}
    >
      <Row gutter={40}>
        <Col span={8}>
          <FormItem {...formItemLayout} label="姓名">
            {getFieldDecorator('name')(
              <Input placeholder="请输入姓名" />
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout} label="手机">
            {getFieldDecorator('mobile')(
              <Input placeholder="请选择手机号码"/>
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout} label="地址">
            {getFieldDecorator('address')(
              <Input placeholder="请选择地址"/>
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout} label="车牌号">
            {getFieldDecorator('license')(
              <Input placeholder="请输入车牌号" />
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout} label="注册时间">
            {getFieldDecorator('reg_time')(
              <DatePicker.RangePicker />
            )}
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Col span={24} style={{ textAlign: 'right' }}>
          <Button type="primary" htmlType="submit">搜索</Button>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
          </Button>
        </Col>
      </Row>
    </Form>
  );
  
});

function mapStateToProps(state) {
  const { query } = state.routing.locationBeforeTransitions
  return {
    query
  };
}

export default connect(mapStateToProps)(AdvancedSearchForm);





